﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mediatheque.Areas.Admin.Models;

namespace mediatheque.Controllers
{
    public class FilmController : Controller
    {
        private Oeuvres myOeuvre = new Oeuvres();

        //
        // GET: /Films/

        public ActionResult Index()
        {
            var list = from g in myOeuvre.oeuvres
                       where g.type == "dvd"
                       select g;

            if (list == null)
                return View("NotFound");
            else
                return View(list.ToList());
        }

        public ActionResult Emprunt(int id)
        {
            if (Session.Count == 0)
            {
                ViewData["warning"] = "Vous devez être connecté pour emprunté!";
                return RedirectToAction("Logon", "Account");
            }

            if (!myOeuvre.isBorrowed(int.Parse(Session["login_id"].ToString()), id, "dvd"))
            {
                emprunts emp = new emprunts
                {
                    media = id,
                    user = int.Parse(Session["login_id"].ToString()),
                    type = "dvd",
                    date_emprunt = DateTime.Now
                };

                if (TryUpdateModel(emp))
                {
                    myOeuvre.emprunts.AddObject(emp);
                    myOeuvre.SaveChanges();
                }
            }

            return RedirectToAction("Details", new { id = id });
        }

        public ActionResult Rendu(int id)
        {
            if (Session.Count == 0)
            {
                return RedirectToAction("Logon", "Account");
            }

            var user = int.Parse(Session["login_id"].ToString());
            var o = myOeuvre.emprunts.Where(c => c.media == id)
                                     .Where(c => c.user == user)
                                     .Where(c => c.back == null)
                                     .Where(c => c.type == "dvd").First();
            o.back = true;
            o.date_retour = DateTime.Now;
            myOeuvre.SaveChanges();

            return RedirectToAction("Details", new { id = id });
        }

        public ActionResult Details(int id)
        {
            var movies = myOeuvre.getMoviesById(id);
            if (movies == null)
                return View("NotFound");
            else
                return View("ficheFilm", myOeuvre);
        }

    }
}
